<?php


function get_user_by_id($uid,$force_refresh=FALSE)
{
	global $db;
	$uid = intval($uid);
	$r = $db->query('SELECT * from Users WHERE id="'.$uid.'" LIMIT 1',FALSE);

	
	if($o = $db->fetch_object($r))
	{
		$o->id = intval($o->id);
		$o->username = stripslashes($o->username);
		$o->nickname = stripslashes($o->nickname);
		$o->city = stripslashes($o->city);
		$o->about_me = stripslashes($o->about_me);
		$o->avatar = stripslashes($o->avatar);
		$data = $o;
		return $data;
	}
	else
	{
		return FALSE;
	}
	return TRUE;
}

function get_user_by_username($uname, $force_refresh=FALSE, $return_id=FALSE)
{
	if( $uname=='' )
	{
		return FALSE;
	}
	//global $cache;
	//$key	= 'uidbyname_'.md5(strtolower($uname));
	//$uid	= $cache->get( $key );
	//if( FALSE!==$uid && TRUE!=$force_refresh )
	//{
	//	return $return_id ? $uid : get_user_by_id($uid);
	//}
	global $db;
	$uid	= FALSE;
	$r	= $db->query('SELECT id FROM users WHERE username="'.$db->escape($uname).'" LIMIT 1', FALSE);
	if( $o = $db->fetch_object($r) )
	{
		$uid	= intval($o->id);
		//$cache->set( $key, $uid, CACHE_EXPIRE );
		return $return_id ? $uid : get_user_by_id($uid);
	}
	return FALSE;
}

function is_valid_username($uname,$check_scripts=FALSE)
{
	if(FALSE == preg_match('/^[a-zA-Z0-9]{4,20}$/',$uname))
	{
		return FALSE;
	}
	if(in_array(strtolower($uname),$GLOBALS['FORBIDDEN_USERNAMES']))
	{
		return FALSE;
	}
	if($check_scripts)
	{
		if(file_exists(PAGES.'pg_'.$uname.'.php'))
		{
			return FALSE;
		}
	}
	return TRUE;
}

function reg_new_user($username,$passwd,$passwdagain,$nickname,$email,$city)
{
	global $db;
	$username = $db->escape($username);
	
	//判断用户名是否被注册
	$o = $db->fetch('SELECT * from Users WHERE username="'.$username.'" LIMIT 1');
	if(FALSE != $o)
		return FALSE;
	
	$passwd = $db->escape($passwd);
	$passwdagain = $db->escape($passwdagain);
	$nickname = $db->escape($nickname);
	$email = $db->escape($email);
	$city = $db->escape($city);
	
	$res = TRUE;
	$res = $res && is_valid_username($username,TRUE);
	$res = $res && (strcmp($passwd,$passwdagain) == 0);
	if(! $res)
	{
		return FALSE;
	}
	$r = $db->query('INSERT INTO Users(username,nickname,password,email,avatar,city,reg_date,reg_ip,lastlogin_date,lastlogin_ip,is_spammer,lastclick_date,lastpost_date,lastemail_date) values("' . $username . '","' . $nickname . '",md5("' . $passwd . '"),"' . $email . '","default_1","' . $city . '",now(),0,now(),0,0,now(),now(),now())');
	return TRUE;
}
?>